package com.ambercrm.base;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.ClipboardManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import androidx.annotation.IdRes;
import androidx.fragment.app.Fragment;

import com.ambercrm.R;
import com.ambercrm.common.Common;
import com.ambercrm.dialog_utils.ProgressDialogUtils;
import com.ambercrm.http.HttpUtils;
import com.ambercrm.tools.RandomTool;
import com.ambercrm.tools.SharedPreferencesHelper;
import com.ambercrm.tools.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;

import de.greenrobot.event.EventBus;

public abstract class BaseFragment extends Fragment {
    public SharedPreferencesHelper sp;
    public Activity mActivity;
    ProgressDialogUtils mProgressDialogUtils;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mActivity = getActivity();
            sp = new SharedPreferencesHelper(mActivity);
            mProgressDialogUtils = new ProgressDialogUtils(mActivity);
            EventBus.getDefault().register(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 代替findViewById
    public <T extends View> T findView(View v, int id) {
        return (T) v.findViewById(id);
    }

    // 弹出Toast
    public void toast(final String msg) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToast(msg);
            }
        });
    }

    public void toast(final int resource) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showToast(resource);
            }
        });
    }

    // 打开一个Activity传递一个Bundle
    public void startActivity(Class<? extends Activity> target, Bundle bundle, boolean finish) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(mActivity, target);
            if (bundle != null) {
                intent.putExtras(bundle);
            }
            mActivity.startActivity(intent);
            mActivity.overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
            if (finish) {
                mActivity.finish();
            }
        }
    }

    // 打开一个Activity传递一个Bundle
    public void startActivityWithoutFastClick(Class<? extends Activity> target, Bundle bundle, boolean finish) {
        Intent intent = new Intent(mActivity, target);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        mActivity.startActivity(intent);
        mActivity.overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
        if (finish) {
            mActivity.finish();
        }
    }

    // 打开一个Activity传递一个字符串
    public void startActivity(Class<? extends Activity> target, String passDataKey, String value, boolean finish) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(mActivity, target);
            if (passDataKey != null && value != null) {
                intent.putExtra(passDataKey, value);
            }
            startActivity(intent);
            mActivity.overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
            if (finish) {
                mActivity.finish();
            }
        }
    }

    // 打开一个Activity传递一个boolean类型
    public void startActivity(Class<? extends Activity> target, String passDataKey, boolean value, boolean finish) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(mActivity, target);
            if (passDataKey != null) {
                intent.putExtra(passDataKey, value);
            }
            startActivity(intent);
            mActivity.overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
            if (finish) {
                mActivity.finish();
            }
        }
    }

    // 打开一个Activity传递一个ArrayList
    public void startActivity(Class<? extends Activity> target, String passDataKey, ArrayList<String> list, boolean finish) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(mActivity, target);
            if (passDataKey != null) {
                intent.putStringArrayListExtra(passDataKey, list);
            }
            startActivity(intent);
            mActivity.overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
            if (finish) {
                mActivity.finish();
            }
        }
    }

    // 打开一个Activity
    public void startActivityForResult(Class<? extends Activity> target, int requestCode, Bundle bundle) {
        if (Common.getInstance().isNotFastClick()) {
            Intent intent = new Intent(mActivity, target);
            if (bundle != null) {
                intent.putExtras(bundle);
            }
            startActivityForResult(intent, requestCode);
            mActivity.overridePendingTransition(R.anim.comm_slide_in_from_right, R.anim.comm_scale_out);
        }
    }

    public void finishActivity() {
        mActivity.finish();
        mActivity.overridePendingTransition(R.anim.comm_scale_in, R.anim.comm_slide_out_to_right);
    }

    // 隐藏软键盘
    public void hideSoftKeyBoard(View view) {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        //隐藏键盘
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    // 显示软键盘
    public void showSoftKeyBoard(View view) {
        view.requestFocus();
        InputMethodManager imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        //显示键盘
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    public DisplayMetrics getScreenParams() {
        DisplayMetrics dm = new DisplayMetrics();
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm;
    }

    // 保存到剪切板
    public void saveToClipboard(String text) {
        ClipboardManager c = (ClipboardManager) mActivity.getSystemService(Service.CLIPBOARD_SERVICE);
        c.setText(text);
        toast("已复制到剪切板");
    }

    //获取随机数， 参数为返回随机数的长度
    public String generateRandomString(int length) {
        return RandomTool.generateString(length);
    }

    // 设置屏幕亮度 0-255
    public void setScreenBrightness(int brightness) {
        Window window = mActivity.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        if (brightness == -1) {
            lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE;
        } else {
            lp.screenBrightness = (brightness < 0 ? 0 : brightness) / 255f;
        }
        window.setAttributes(lp);
    }

    // 获取屏幕亮度
    public int getSystemBrightness() {
        int systemBrightness = 0;
        try {
            systemBrightness = Settings.System.getInt(mActivity.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
            if (systemBrightness < 100) {
                systemBrightness = 100;
            }
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return systemBrightness;
    }

    public <T extends View> T getElementView(@IdRes int resId) {
        return (T) getView().findViewById(resId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        sp = null;
        mActivity = null;
        EventBus.getDefault().unregister(this);
        if (mProgressDialogUtils.isShowing()) {
            mProgressDialogUtils.dismiss();
        }
    }

    // 界面请求封装
    HttpUtils.OnResponseListener onResponseListener = new HttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(final String result, final int what) {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    BaseFragment.this.onSucceed(result, what);
                }
            });
        }

        @Override
        public void onFailed(final String result, final int what) {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    BaseFragment.this.onFailed(result, what);
                }
            });

        }

        @Override
        public void onFinish(final int what) {
            mActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    BaseFragment.this.onFinish(what);
                }
            });
        }
    };

    protected void httpGet(String url, HashMap<String, String> params, int what, boolean isShowProgressDialog, String progressText) {
        if (isShowProgressDialog) {
            if (progressText != null) {
                mProgressDialogUtils.show(mActivity, progressText, false, null);
            }
            else {
                mProgressDialogUtils.show(mActivity);
            }
        }
        HttpUtils.httpGet(url, params, onResponseListener, what);
    }

    protected void httpPost(String url, int what, Object params, boolean isShowProgressDialog, String progressText) {
        if (isShowProgressDialog) {
            if (progressText != null) {
                mProgressDialogUtils.show(mActivity, progressText, false, null);
            }
            else {
                mProgressDialogUtils.show(mActivity);
            }
        }
        HttpUtils.httpPost(url, params, onResponseListener, what);
    }

    // 请求成功回调
    protected void onSucceed(String result, int what) {

    }

    // 请求失败回调
    protected void onFailed(String result, int what) {

    }

    // 请求完成回调
    protected void onFinish(int what) {
        if (mProgressDialogUtils != null) {
            mProgressDialogUtils.dismiss();
        }
    }
}
